package com.sf.fy.uav.applet.utils.exception;

import com.sf.fy.uav.common.exception.BusinessException;
import com.sf.fy.uav.common.utils.ResultCode;
import com.sf.fy.uav.common.utils.Rs;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author LTQ
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Rs globalException(HttpServletResponse response, RuntimeException ex) {
        log.info("GlobalExceptionHandler...");
        log.info("错误代码：" + response.getStatus());
        String msg;
        if (ObjectUtils.isEmpty(ex.getCause())) {
            msg = ex.getMessage();
            log.info(ex.getMessage());
        } else {
            msg = ex.getCause().getMessage();
            log.info(ex.getCause().getMessage());
        }
        return Rs.failed(msg);
    }

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Rs globalException(HttpServletResponse response, BusinessException ex) {
        log.info("GlobalExceptionHandler...");
        log.info("错误代码：" + response.getStatus());
        log.info(ex.getMessage());
        ResultCode resultCode = new ResultCode() {
            @Override
            public Integer getCode() {
                return ex.getError().getErrCode();
            }
        };
        return Rs.failed(resultCode, ex.getErrDetail());
    }
}
